from random import randint

from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.db.migrations import serializer
from django import forms
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Users
from utils.serializers import UserSerializer, UserLoginSerializer, UserRegistrationSerializer


# Create your views here.


class UserViewSet(viewsets.ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
#真的
class UserRegistrationView(APIView):
    def post(self,request):
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            try:
                Users.objects.get(username=username)
                messages.error(request, '用户已存在')
                return redirect('/register')
            except :
                id=randint(0, 99999)
                user = Users.objects.create(userid=str(id).ljust(5),username=username,roletype=0)
                user.password=password
                user.save()
                return redirect('/')  # 重定向到首页
        return render(request, 'register.html')
    def get(self,request):
        return render(request, 'register.html')


# class UserLoginAPIView(APIView):
#     def post(self, request):
#         data = request.data
#         username = data["username"]
#         password = data["password"]
#         password=password.ljust(20)
#         try :
#             tempUser = Users.objects.get(username = username)
#             if (password == tempUser.password):
#                 response = JsonResponse({'message': 'Login successful'})
#                 response.set_cookie(key='session',value=tempUser.username)
#                 return render(request, 'login.html', response)
#             else:
#                 return HttpResponse("login failed")
#         except :
#             return HttpResponse("user not found")
#     def get(self,request):
#         return render(request, 'login.html', {})



def index(request):
    context = {'key': 'value'}  # 你可以在这里添加需要传递给模板的上下文数据
    return render(request, 'index.html', context)

def log_out(request):
    logout(request)
    return redirect('/')


def log_in(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        password=password.ljust(20)
        try:
            user = Users.objects.get(username=username)
            if user.password == password:
                # 验证成功，重定向到首页
                request.session['username'] = user.username  # 将用户 ID 存储在会话中
                request.session['userid'] = user.userid
                request.session['is_active']=True
                if(user.roletype==0 and user.roletype=='0  '):
                    request.session['roletype'] = 0
                elif(user.roletype==1 or user.roletype=='1  '):
                    request.session['roletype'] = 1
                elif(user.roletype!=2 or user.roletype=='2  '):
                    request.session['roletype'] = 2
                return redirect('/')
            else:
                messages.error(request, 'Invalid password.')
        except Users.DoesNotExist:
            messages.error(request, 'Invalid username.')

    return render(request, 'login.html')


class Home(APIView):
    def get(self, request):
        username = request.session.get('username')  # 直接获取用户名
        if username:
            user = Users.objects.get(username=username)
            return render(request, 'home.html', {'username': username})
        else:
            return HttpResponse("用户未登录", status=401)



#class UserForm(forms.ModelForm):
#     class Meta:
#         model = Users
#         fields = ['email', 'password', 'tel']
#         widgets = {
#             'email': forms.TextInput(attrs={'class': 'form-control'}),
#             'password': forms.TextInput(attrs={'class': 'form-control'}),
#             'tel': forms.TextInput(attrs={'class': 'form-control'}),
#         }

from django import forms

class UserProfileForm(forms.Form):
    email = forms.EmailField(label='邮箱',required=False)
    password = forms.CharField(label='密码', widget=forms.PasswordInput,required=False)
    tel = forms.CharField(label='电话',required=False)

class personal(APIView):
    def get(self, request):
        username = request.session.get('username')  # 直接获取用户名
        if username:
            form = UserProfileForm()
            return render(request, 'personal.html', {'form': form})
        else:
            return HttpResponse("用户未登录", status=401)
    def post(self,request):
        username = request.session.get('username')
        action = request.POST.get('action')
        if action == '1':
            # 执行增加操作的逻辑
            return HttpResponse("执行了增加操作")
        elif action == '2':
            # 执行删除操作的逻辑
            Users.objects.filter(username=username).delete()
            logout(request)
            return redirect('/')
        elif action == '3':
            # 执行修改操作的逻辑
            form = UserProfileForm(request.POST)
            if form.is_valid():
                # 处理表单数据，例如更新数据库中的用户信息
                # 这里假设你有一个User模型
                user = Users.objects.get(username=username)  # 获取当前用户
                user.email = form.cleaned_data['email']
                user.password = form.cleaned_data['password']
                user.tel = form.cleaned_data['tel']
                user.save()
                return HttpResponse("用户信息修改成功")
            else:
                messages.error(request, "表单数据有误，请检查后重新提交")
                return render(request, 'personal.html', {'form': form})
        elif action == '4':
            form = UserProfileForm(request.POST)
            user = Users.objects.get(username=username)
            # 执行查询操作的逻辑
            return render(request, 'personal.html', {'user': user,'form':form})
        else:
            return HttpResponse("未知操作")
